#!/bin/bash

# 该脚本将在MySQL容器内运行，用于创建用户和设置权限

# 等待MySQL完全启动
echo "等待MySQL启动..."
until mysqladmin ping -h"localhost" --silent; do
    sleep 1
done

# 获取随机生成的root密码
ROOT_PASSWORD=$(grep 'temporary password' /var/log/mysql/error.log | awk '{print $NF}' || cat /var/lib/mysql/.mysql_secret | grep -v "#" | cut -d' ' -f6)

# 生成随机密码给learn用户
LEARN_PASSWORD=$(openssl rand -hex 8)

# 创建learn用户和数据库
mysql -uroot -p${ROOT_PASSWORD} --connect-expired-password <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewRootPassword123!';
CREATE DATABASE IF NOT EXISTS learn;
CREATE USER IF NOT EXISTS 'learn'@'%' IDENTIFIED BY '${LEARN_PASSWORD}';
GRANT ALL PRIVILEGES ON learn.* TO 'learn'@'%';
FLUSH PRIVILEGES;
EOF

# 将密码保存到文件
echo "数据库用户: learn" > /mysql_credentials.txt
echo "数据库密码: ${LEARN_PASSWORD}" >> /mysql_credentials.txt

# 复制到共享卷，让主容器可以访问
mkdir -p /var/lib/mysql/credentials
cp /mysql_credentials.txt /var/lib/mysql/credentials/

echo "MySQL用户已创建，密码已保存到 /mysql_credentials.txt 和共享卷中" 